﻿#include <iostream>
#include <vector>

/**
 * 测试copy构造函数，对于派生类，需要用生成对象指针，才能很好的使用虚函数
 */ 
using namespace std;
class Base {
public:
    Base(int initialvalue = 0): x(initialvalue) {
        cout << "Base Constructor." << endl;
    }
    Base(const Base& rhs): x(rhs.x) {
        cout << "Base Copy Constructor." << endl;
    }

    virtual void printSelf() {
        cout << "Base:" << x << endl;
    }
private:
    int x;
};

class Derived: public Base {
public:
    Derived(int initialvalue)
        : Base(initialvalue), y(initialvalue) {
        cout << "Derived Constructor." << endl;
    }

    Derived(const Derived& rhs) // 错误的拷贝
        : y(rhs.y) {
        cout << "Derived Copy Constructor." << endl;
    } // 构造函数

    virtual void printSelf () override {
        cout << "Derived:" << y << endl;
    }

private:
    int y;
};

struct DataGroup 
{
    double vf = 0.0; // 普通变量
    double vfs[3] {0, 0, 0};  // 数组
    vector<int> vecs;
    DataGroup *dataGroup = nullptr;

    void printSelf() {
        cout << "vf:" << vf << ", vfs:" << vfs[0] << "," << vfs[1] << "," << vfs[2] << endl;
        cout << "vecs:" << &vecs << " {";
        for(size_t i = 0; i < vecs.size(); i++) {
            cout << vecs[i] << ",";
        }
        cout << endl;
        cout << "dataGroup address: " << dataGroup << endl;
    }
};

int main(int argc, char *argv[])
{
    Base base(1);
    Derived derived(2);

    // 如果是 Base obj = derived;  那么obj真的指向Base类了。
    Base *obj = &derived;

    cout << "Test Derived copy constructor:" << endl;
    base.printSelf();
    derived.printSelf();
    obj->printSelf();

    cout << "Test default copy contstructor:====" << endl;
    DataGroup dataGroup1;
    dataGroup1.vecs.push_back(5);
    dataGroup1.vecs.push_back(7);
    DataGroup dataGroup2 = dataGroup1;
    dataGroup1.vf = 1.0;
    dataGroup1.vfs[2] = 3.0;
    dataGroup1.dataGroup = &dataGroup2;
    dataGroup1.vecs[0] = 6;

    DataGroup dataGroup3;
    dataGroup3 = dataGroup1;
    dataGroup3.dataGroup = &dataGroup1;

    dataGroup1.printSelf();
    dataGroup2.printSelf();
    dataGroup3.printSelf();

    getchar();

    return 0;
}
